package com.example.treehole.fragmnet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.treehole.R;
import com.example.treehole.activity.DynamicDetailActivity;
import com.example.treehole.adapter.DynamicHomeAdapter;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.DynamicResponse;
import com.example.treehole.utils.ConvertEntityUtils;
import com.example.treehole.viewobject.DynamicOutSide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link fragment1Child#newInstance} factory method to
 * create an instance of this fragment.
 */
public class fragment1Child extends BaseFragment {

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    List<DynamicOutSide> data=new ArrayList<>();
    DynamicHomeAdapter adapter;
    int categoryId;
    int selectId;
    int pageNum=1;

    //categoryId 热榜/推荐   selectId -五个按钮
    public static fragment1Child newInstance(int categoryId,int selectId) {
        fragment1Child fragment1Child = new fragment1Child();
        fragment1Child.categoryId = categoryId;
        fragment1Child.selectId = selectId;
        return fragment1Child;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                adapter.setData(data);
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.fragment1_child;
    }

    @Override
    protected void initData(View view) {
        adapter=new DynamicHomeAdapter(getActivity());
        adapter.setOnMyItemClickListener(new DynamicHomeAdapter.OnItemClickListener() {
            @Override
            public void onClick(int pos) {
                Intent intent=new Intent(getActivity(),DynamicDetailActivity.class);
                intent.putExtra("id",data.get(pos).getId());
                startActivity(intent);
            }
        });
        loadData(true);
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        recyclerView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum=1;
                loadData(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData(false);
            }
        });
    }

    private void loadData(boolean isRefresh) {
        String url=categoryId==0?ApiConfig.GET_DYNAMIC_COMMEND:ApiConfig.GET_DYNAMIC_HOT;
        HashMap<String,String> map=new HashMap<>();
        map.put("page",String.valueOf(pageNum));
        map.put("index",String.valueOf(selectId));
        Api.config(url,map).getRequest(getContext(), new Callback() {
            @Override
            public void onSuccess(String res) {
                if (isRefresh){
                    refreshLayout.finishRefresh(true);
                }else{
                    refreshLayout.finishLoadMore(true);
                }
                try {
                    DynamicResponse dynamicResponse=new Gson().fromJson(res,DynamicResponse.class);
                    String code=dynamicResponse.getCode();
                    if (code.equals("200")){
                        List<DynamicResponse.DataDTO> dataDTOS=dynamicResponse.getData();
                        if (dataDTOS==null){
                            showToastSync(getString(R.string.no_more_data));
                            return;
                        }
                        List<DynamicOutSide> newData= ConvertEntityUtils.convertToDynamicOutSide(dataDTOS);
                        if (isRefresh){
                            data=newData;
                        }else{
                            data.addAll(newData);
                        }
                        mHandler.sendEmptyMessage(1);
                    }else{
                        showToastSync(dynamicResponse.getMsg());
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    showToastSync(e.getMessage());
                }
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                if (isRefresh){
                    refreshLayout.finishRefresh(true);
                }else{
                    refreshLayout.finishLoadMore(true);
                }
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            pageNum=1;
            loadData(true);
        }
    }
}